package com.whut.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.whut.mapper.AppversionMapper;
import com.whut.model.Appversion;
import com.whut.model.UrlProperties;
import com.whut.utils.FormatDate;
import com.whut.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Controller
@RequestMapping("/appVersion")
@Scope("prototype")
public class AppVersionController {

    @Autowired
    private UrlProperties urlProperties;
    @Resource
    private AppversionMapper appversionMapper;
    /*
     * @Author fuzhenjie
     * @Description 存app
     * @Date 12:39 19.6.26
     * @Param [urlStr, fileName]
     * @return java.lang.Object
     **/
    @ResponseBody
    @PostMapping("/uploadApp")
    public String uploadApp(String urlStr,String version,String log) throws Exception{
        //String urlStr = urlProperties.getAddress()+"/examples/files/yiruiapp1_1_3.apk";
        //String savePath = "C:\\Users\\13983\\Desktop\\testQrcode";
        //服务器存放apk包的物理路径
        String savePath = "D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\examples\\files";
        String fileName = "yiruiapp"+version+".apk";
        try{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(savePath);
            if(!saveDir.exists()){
                saveDir.mkdirs();
            }
            File file = new File(saveDir+ File.separator+fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if(fos!=null) {
                fos.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            System.out.println("info:"+url+" download success");
            Appversion appversion = new Appversion();
            appversion.setDownloadLink(urlProperties.getAddress()+"/examples/files/"+fileName);
            appversion.setVersion(version);
            appversion.setIsHead("N");
            appversion.setUploadTime(FormatDate.getDateStringYMDHms());
            appversion.setVersionLog(log);
            appversionMapper.insert(appversion);
            new Thread(new Runnable() {
                public void run() {
                    String qrcode = QRCodeUtil.generateQRCodeURL(appversion.getDownloadLink(),appversion.getVersion());
//                    appversion.setQrCode(qrcode);
                    //因为在这个地方，appversion创建的时候，没有id值的，会有一个默认值，所以一直都修改不到，所以就需要根据刚才设置的一个事情来得到这些数据
                    appversionMapper.updateAppversionByVersion(version,qrcode);
//                    appversionMapper.updateByPrimaryKey(appversion);
                }
            }).start();//开启线程
            return "succ";
        }catch(Exception e){
            e.printStackTrace();
            return "error";
        }

    }

    /*
     * @Author fuzhenjie
     * @Description 取得最近五个版本的app信息
     * @Date 15:22 19.6.26
     * @Param []
     * @return java.lang.Object
     **/
    @ResponseBody
    @PostMapping("/getList")
    public Object getList(){
        return appversionMapper.getList();
    }


    /*
     * @Author fuzhenjie
     * @Description 设定新的最新版本
     * @Date 15:23 19.6.26
     * @Param [mkey]
     * @return java.lang.Object
     **/
    @ResponseBody
    @PostMapping("/setLatest")
    public String getList(int mkey){
        try{
            appversionMapper.updateOldVersionState();
            Appversion appversion = new Appversion();
            appversion.setMkey(mkey);
            appversion.setIsHead("Y");
            appversionMapper.updateByPrimaryKeySelective(appversion);
            return "succ";
        }catch(Exception e){
            e.printStackTrace();
            return "error";
        }
    }


    /*
     * @Author fuzhenjie
     * @Description 取得现在版本的日志
     * @Date 18:11 19.6.26
     * @Param [curVer]
     * @return java.lang.Object
     **/
    @ResponseBody
    @PostMapping("/getCurLog")
    public Object getCurLog(String curVer){
        Appversion appversion = appversionMapper.getByVersionName(curVer);
        JSONArray jsonArray = new JSONArray();
        try {
            jsonArray = JSONArray.parseArray(appversion.getVersionLog());
        }catch (Exception e){
            return new JSONArray();
        }
        return jsonArray;
    }


    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    @ResponseBody
    @PostMapping("/getLatestAppSrc")
    public String getLatestAppSrc()
    {
        return appversionMapper.getLatestVersion().getQrCode();
    }
}
